<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：角色管理控制器
 * 作者：王楠
 * 创建日期：2017-09-11
 */
class RoleController extends CommonController {

    /**
     * 角色列表
     */
    public function rolelist() {
	$app_code = $this->app_code;
	$admin_role_id = $this->admin_role_id;
	$admin_role_level = $this->admin_role_level;
	$role_level_enum = getenumbykey('adminrole_level');
	$appname_arr = $this->getapplist();
	$appname_enum = $this->getenumbyarr($appname_arr);
	$appcode = trim(I('ddlapp', '0'));
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    } else if ($appcode == '') {
		$map['app_flag'] = array(array('exp', 'is null'), array('eq', ''), 'or');
	    }
	}
	$map['state'] = '1';
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	$keyword = trim(I('txtkeyword'));
	if (!empty($keyword)) {
	    $map['name'] = array('like', '%' . $keyword . '%');
	}
	$model = M('chat_adminrole');
	if (!empty($admin_role_id)) {
	    $map['level'] = array('gt', $admin_role_level);
	}
	$total = $model->where($map)->count();
	$row = '10';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$data = $model->where($map)->limit($page->listfirst, $page->listRows)->order('ctime desc')->select();
	$map2['state'] = '1';
	$powerModel = M('chat_adminpower');
	$data_power = $powerModel->where($map2)->where(array('pid' => '0'))->order('sort asc, ctime asc, id asc')->select();
	$data_power2 = $powerModel->where($map2)->where(array('pid' => array('gt', '0')))->order('sort asc, ctime asc, id asc')->select();
	foreach ($data as $key => $value) {
	    $data[$key]['appname'] = $appname_enum[$data[$key]['app_flag']];
	    $data[$key]['role_valid'] = empty($admin_role_id) ? 1 : ($data[$key]['level'] > $admin_role_level ? 1 : 0);
	    $data[$key]['level'] = $role_level_enum[$data[$key]['level']];
	    $data[$key]['ctime'] = date("Y-m-d H:i", $data[$key]['ctime']);
	    $level_first_id = $value['level_first_id'];
	    if (!empty($level_first_id)) {
		$level_first_id = explode(',', $level_first_id);
	    }
	    $level_second_id = $value['level_second_id'];
	    if (!empty($level_second_id)) {
		$level_second_id = explode(',', $level_second_id);
	    }
	    $index = 0;
	    foreach ($data_power as $k => $v) {
		if ($index > 2 && count($level_first_id) > $index) {
		    $data[$key]['power'] .= '…';
		    break;
		}
		foreach ($level_first_id as $kk => $vv) {
		    if ($v['id'] == $vv && $v['pid'] == 0) {
			$count_second = 0;
			foreach ($data_power2 as $kkk => $vvv) {
			    foreach ($level_second_id as $kkkk => $vvvv) {
				if ($vvv['id'] == $vvvv && $vvv['pid'] == $v['id']) {
				    $count_second++;
				}
			    }
			}
			$index2 = 0;
			$data[$key]['power'] .= '<b>' . $v['name'] . '</b>【';
			foreach ($data_power2 as $kkk => $vvv) {
			    if ($index2 > 1 && $count_second > $index2 && $vvv['pid'] == $v['id']) {
				$data[$key]['power'] .= '，…';
				break;
			    }
			    foreach ($level_second_id as $kkkk => $vvvv) {
				if ($vvv['id'] == $vvvv && $vvv['pid'] == $v['id']) {
				    if ($index2) {
					$data[$key]['power'] .= '，' . $vvv['name'];
				    } else {
					$data[$key]['power'] .= $vvv['name'];
				    }
				    $index2++;
				}
			    }
			}
			if ($index == count($level_first_id) - 1) {
			    $data[$key]['power'] .= '】';
			} else {
			    $data[$key]['power'] .= '】，';
			}
			$index++;
		    }
		}
	    }
	}
	$search = array('appsel' => $appcode, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime,);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'search' => $search,
	    'app_code' => $app_code,
	    'apparr' => $this->getapplist()
	));
	$this->display();
    }

    /**
     * 角色详情
     */
    public function roledetail() {
	$app_code = $this->app_code;
	$id = I('id');
	if (!empty($id)) {
	    $appname_arr = $this->getapplist();
	    $appname_enum = $this->getenumbyarr($appname_arr);
	    $adminroleModel = M('chat_adminrole');
	    $data_role = $adminroleModel->where(array('id' => $id))->find();
	    $appcode = $data_role['app_flag'];
	    $appname = $appname_enum[$appcode];
	    $rolename = $data_role['name'];
	    $rolelevel = $data_role['level'];
	    $level_first_id = $data_role['level_first_id'];
	    $level_second_id = $data_role['level_second_id'];
	    $level_third_id = $data_role['level_third_id'];
	    $ctime = date('Y-m-d H:i', $data_role['ctime']);
	    $map['state'] = '1';
	    $model = M('chat_adminpower');
	    $data = $model->where($map)->where(array('id' => array('in', $level_first_id)))->where(array('pid' => array('eq', '0')))->order('sort asc, ctime asc, id asc')->select();
	    $data2 = $model->where($map)->where(array('id' => array('in', $level_second_id)))->where(array('pid' => array('gt', '0')))->order('sort asc, ctime asc, id asc')->select();
	    foreach ($data as $key => $value) {
		$data_son = array();
		foreach ($data2 as $key2 => $value2) {
		    if ($value2['pid'] == $value['id']) {
			array_push($data_son, $value2);
		    }
		}
		$data[$key]['data'] = $data_son;
	    }
	}
	$this->assign(array(
	    'id' => $id,
	    'appname' => $appname,
	    'name' => $rolename,
	    'level' => $rolelevel,
	    'ctime' => $ctime,
	    'app_code' => $app_code,
	    'appcode' => $appcode,
	));
	$this->assign('data', $data);
	$this->display();
    }

    /**
     * 角色编辑（添加，修改）
     */
    public function roleadd() {
	$app_code = $this->app_code;
	$admin_role_id = $this->admin_role_id;
	$admin_role_level = $this->admin_role_level;
	$role_level_enum = getenumbykey('adminrole_level');
	$role_level_arr = getarrbyenum($role_level_enum);
	$map_level_first = array();
	$map_level_second = array();
	if ($admin_role_id) {
	    foreach ($role_level_arr as $key => $value) {
		if ($admin_role_level >= $value['value']) {
		    array_splice($role_level_arr, $key, 1);
		}
	    }
	    $adminroleModel = M('chat_adminrole');
	    $data_role = $adminroleModel->where(array('id' => $admin_role_id))->find();
	    $level_first_id = $data_role['level_first_id'];
	    $level_second_id = $data_role['level_second_id'];
	    $level_third_id = $data_role['level_third_id'];
	    $map_level_first = array('id' => array('in', $level_first_id));
	    $map_level_second = array('id' => array('in', $level_second_id));
	}
	if (!empty($app_code)) {
	    $map['app_flag'] = array(array('exp', 'is null'), array('eq', '1'), 'or');
	} else {
	    $map['app_flag'] = array(array('exp', 'is null'), array('eq', '2'), 'or');
	}
	$map['state'] = '1';
	$model = M('chat_adminpower');
	$data = $model->where($map)->where($map_level_first)->where(array('pid' => array('eq', '0')))->order('sort asc, ctime asc, id asc')->select();
	$data2 = $model->where($map)->where($map_level_second)->where(array('pid' => array('gt', '0')))->order('sort asc, ctime asc, id asc')->select();
	foreach ($data as $key => $value) {
	    $data_son = array();
	    foreach ($data2 as $key2 => $value2) {
		if ($value2['pid'] == $value['id']) {
		    array_push($data_son, $value2);
		}
	    }
	    $data[$key]['data'] = $data_son;
	}
	$id = I('id');
	$btnname = '添加';
	$columnname = '添加角色';
	if (!empty($id)) {
	    $columnname = '修改角色';
	    $btnname = '修改';
	    $adminroleModel = M('chat_adminrole');
	    $data_role = $adminroleModel->where(array('id' => $id))->find();
	    $appcode = $data_role['app_flag'];
	    $role_name = $data_role['name'];
	    $role_level = $data_role['level'];
	    $level_first_id = $data_role['level_first_id'];
	    $ctime = date('Y-m-d H:i', $data_role['ctime']);
	    if (!empty($level_first_id)) {
		$level_first_id = explode(',', $level_first_id);
	    }
	    $level_second_id = $data_role['level_second_id'];
	    if (!empty($level_second_id)) {
		$level_second_id = explode(',', $level_second_id);
	    }
	    $level_third_id = $data_role['level_third_id'];
	    foreach ($data as $k => $v) {
		foreach ($level_first_id as $kk => $vv) {
		    if ($v['id'] == $vv) {
			$data[$k]['checked'] = "checked = 'checked'";
		    }
		}
		foreach ($data[$k]['data'] as $k2 => $v2) {
		    foreach ($level_second_id as $kk2 => $vv2) {
			if ($v2['id'] == $vv2) {
			    $data[$k]['data'][$k2]['checked'] = "checked = 'checked'";
			}
		    }
		}
	    }
	    foreach ($role_level_arr as $key => $value) {
		if ($value['value'] == $role_level) {
		    $role_level_arr[$key]["role_level_selected"] = "selected='selected'";
		}
	    }
	}

	$this->assign(array(
	    'id' => $id,
	    'appcode' => $appcode,
	    'name' => $role_name,
	    'level' => $role_level,
	    'ctime' => $ctime,
	    'apparr' => $this->getapplist(),
	));
	$this->assign('columnname', $columnname);
	$this->assign('btnname', $btnname);
	$this->assign('rolelevelarr', $role_level_arr);
	$this->assign('data', $data);
	$this->display();
    }

    /**
     * 角色编辑（添加，修改）提交
     * @return type
     */
    public function roleaddsubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	}
	$app_code = $this->app_code;
	if (empty($app_code)) {
	    $app_code = I('app_code');
	}
	$admin_id = $this->admin_id;
	$admin_role_id = $this->admin_role_id;
	$admin_role_level = $this->admin_role_level;
	$id = I('id');
	$rolename = trim(I('rolename'));
	$rolelevel = I('rolelevel');
	$level_first_id = I('level_first_id');
	$level_second_id = I('level_second_id');
	$level_third_id = I('level_third_id');
	if (empty($rolename)) {
	    $response = array('ret' => '1002', 'code' => '角色名称不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
//	if (empty($rolelevel)) {
//	    $response = array('ret' => '1002', 'code' => '角色等级不能为空！');
//	    return $this->ajaxReturn($response, 'json');
//	}
	if (!count($level_first_id) || !count($level_second_id)) {
	    $response = array('ret' => '1002', 'code' => '角色权限不能为空！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    $map['app_flag'] = array(array('exp', 'is null'), array('eq', ''), 'or');
	}
	$map['state'] = array('neq', '2');
	$map['name'] = $rolename;
	if (!empty($id)) {
	    $map['id'] = array('neq', $id);
	}
	$model = M('chat_adminrole');
	if ($model->where($map)->count()) {
	    $response = array('ret' => '1002', 'code' => '对不起，该角色名称已存在！');
	    return $this->ajaxReturn($response, 'json');
	}
	if (!empty($level_first_id) && count($level_first_id)) {
	    $level_first_id = implode(',', array_unique($level_first_id));
	}
	if (!empty($level_second_id) && count($level_second_id)) {
	    $level_second_id = implode(',', array_unique($level_second_id));
	}
	if (!empty($level_third_id) && count($level_third_id)) {
	    $level_third_id = implode(',', array_unique($level_third_id));
	}
	$data['name'] = $rolename;
	$data['level_first_id'] = $level_first_id;
	$data['level_second_id'] = $level_second_id;
	$data['level_third_id'] = $level_third_id;
	if (empty($id)) {
	    $data['admin_id'] = $admin_id;
	    $data['level'] = empty($admin_role_id) ? '1' : (string) ($admin_role_level + 1);
	    $data['state'] = '1';
	    $data['ctime'] = time();
	    if (!empty($app_code)) {
		$data['app_flag'] = $app_code;
	    }
	}
	if (!empty($id)) {
	    if ($model->where(array('id' => $id))->save($data)) {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    } else {
		$response = array('ret' => '1001', 'code' => '修改成功！');
	    }
	} else {
	    if ($model->add($data)) {
		$response = array('ret' => '1001', 'code' => '添加成功！');
	    } else {
		$response = array('ret' => '1002', 'code' => '添加失败！');
	    }
	}
	return $this->ajaxReturn($response, 'json');
    }

    /**
     * 删除角色提交
     * @return type
     */
    public function deletesubmit() {
	$id = I('id');
	if (!empty($id)) {
	    $model = M('chat_adminrole');
	    $adminModel = M('chat_admin');
	    $data = $model->where(array('id' => $id))->find();
	    if ($data) {
		$count_admin = $adminModel->where(array('role_id' => $id, 'state' => array('neq', '3')))->count();
		if ($count_admin) {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该角色正在使用，无法删除！'));
		}
		$data['state'] = '2';
		$result = $model->save($data);
		if ($result) {
		    return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！'));
		} else {
		    return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！'));
		}
	    } else {
		return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该角色可能已被删除！'));
	    }
	}
    }

}
